/* this file contains the ChatFragment activity, 
 * with the buttons and the history of message.
 * The layout is in the file chat_details.xml. 
 * The buttons are to be implemented in this file. */
package dk.aau.walkietalkieui.fragment;

import java.util.ArrayList;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import dk.aau.walkietalkie.audio.VoicePlayer;
import dk.aau.walkietalkie.audio.VoiceRecorder;
import dk.aau.walkietalkie.database.DBController;
import dk.aau.walkietalkie.database.Identification;
import dk.aau.walkietalkie.network.MessageSenderF;
import dk.aau.walkietalkie.network.MessageSendingViaNetwork;
import dk.aau.walkietalkie.network.NetworkHelper;
import dk.aau.walkietalkie.network.TCPClientFileTransfer;
import dk.aau.walkietalkie.network.UDPBroadcastReceiver;
import dk.aau.walkietalkie.network.UDPBroadcastSender;
import dk.aau.walkietalkie.picture.MyCamera;
import dk.aau.walkietalkie.picture.SendPicture;
import dk.aau.walkietalkieui.ChatActivity;
import dk.aau.walkietalkieui.IMessageNotifier;
import dk.aau.walkietalkieui.R;
import dk.aau.walkietalkieui.WalkieTalkieApplication;
import dk.aau.walkietalkieui.adapter.ChatMessageAdapter;
import dk.aau.walkietalkieui.message.MyMessage;

public class ChatFragment extends Fragment implements IMessageNotifier {
	private static final String SELECTED_NAME = "SelectedName";
	private static final String SELECTED_IP = "SelectedIp";
	public static String KEY_SELECTED_INDEX = "selIndex";
	public static final String TAG = "ChatFragment";
	private MyCamera cam;
	private static String current_destiny_ip = null;
	private VoiceRecorder vr = new VoiceRecorder();
	private VoicePlayer vp = new VoicePlayer();
	private int selectedIndex;
	private Button btnSend;
	private View root;
	private static String selectedName;
	private static String selectedIp;
	private static ChatMessageAdapter adapterChat;

	public static ChatFragment newInstance(int selectedIndex,
			String selectedName, String selectedIp) {
		ChatFragment chatFg = new ChatFragment();
		Bundle args = new Bundle();
		args.putInt(KEY_SELECTED_INDEX, selectedIndex);
		args.putString(SELECTED_NAME, selectedName);
		args.putString(SELECTED_IP, selectedIp);
		chatFg.setArguments(args);
		return chatFg;

	}

	private static String getMyIp() {
		return NetworkHelper.getDottedDecimalIP(NetworkHelper
				.getLocalIPAddress());
	}

	private static final String getMyName() {
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(WalkieTalkieApplication
						.getContext());
		return sp.getString("prefUsername", "Unknown");
	}

	private final Identification getMyIdentification() {

		String ip = getMyIp();
		String name = getMyName();
		Identification me = new Identification(ip, name, 0);
		return me;

	}

	private static Identification getCurrentContactIdentification() {

		String ip = selectedIp;
		String name = selectedName;
		Identification you = new Identification(ip, name, 0);
		return you;

	}

	@Override
	public void onStart() {
		super.onStart();

		// set this fragment as the new message notifier for the tcp file
		// receiver
		WalkieTalkieApplication.getApplication().getTranferReceiver()
				.setMessageNotifier(this);
		//Try to see the message added before onStart was called
		//but adapterChat is empty 
		//adapterChat.notifyDataSetChanged();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// // set this fragment as the new message notifier for the tcp file
		// receiver
		// WalkieTalkieApplication.getApplication().getTranferReceiver().setMessageNotifier(this);

		if (savedInstanceState != null) {
			selectedIndex = savedInstanceState.getInt(KEY_SELECTED_INDEX, -1);
			selectedName = savedInstanceState.getString(SELECTED_NAME,
					"Unknown");
			selectedIp = savedInstanceState.getString(SELECTED_IP, "0.0.0.0");

		} else {
			Bundle args = getArguments();
			if (args != null) {
				selectedIndex = args.getInt(KEY_SELECTED_INDEX, -1);
				selectedName = args.getString(SELECTED_NAME);
				selectedIp = args.getString(SELECTED_IP);// , "0.0.0.0");

			} else {
				selectedIndex = -1;
				selectedName = "Unknown";
				selectedIp = "0.0.0.0";
			}

		}
		// Displays the name of the contact in the conversation chat
		getActivity().setTitle(selectedName);
		// getActivity().setTitle(adapter.getItem(selectedIndex).getName());
		// current_destiny_ip = adapter.getItem(selectedIndex).getIp();
		getActivity().setTitleColor(getResources().getColor(R.color.white));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		root = inflater.inflate(R.layout.chat_details, null);

		btnSend = (Button) root.findViewById(R.id.btnSend);
		btnSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Send Button
				EditText etMessage = (EditText) root
						.findViewById(R.id.etMessage);
				sendMessage(etMessage.getText().toString(),
						System.currentTimeMillis(),
						MyMessage.MessageType.TYPE_TEXT);
				etMessage.setText("");
			}
		});
		Button btnRecord = (Button) root.findViewById(R.id.btnRecord);
		btnRecord.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					vr.startRecording("");
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					vr.stopRecording();
					String VOICE_PATH = Environment
							.getExternalStorageDirectory().getAbsolutePath()
							+ "/audiorecordtest.3gp";
					sendMessage(VOICE_PATH, System.currentTimeMillis(),
							MyMessage.MessageType.TYPE_RECORD);
				}
				return false;
			}
		});

		Button btnPhoto = (Button) root.findViewById(R.id.btnTakePicture);
		btnPhoto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ChatActivity act = (ChatActivity) getActivity();
				act.showPopupWindowPhoto(R.layout.popup_take_picture,
						R.id.btnPopUpDismissPicture, v, act);
			}
		});

		ListView lv = (ListView) root.findViewById(R.id.listview);
		Object objChat = getActivity().getLastCustomNonConfigurationInstance();
		if (null != objChat) {
			adapterChat = (ChatMessageAdapter) objChat;
		} else {
			adapterChat = new ChatMessageAdapter(getActivity()
					.getApplicationContext());
		}

		lv.setAdapter(adapterChat);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {
				MyMessage msg = adapterChat.getItem(position);
				if (MyMessage.MessageType.TYPE_RECORD.equals(msg.getType())) {
					vp.startPlaying(msg.getDataPath());
				} else if (MyMessage.MessageType.TYPE_PICTURE.equals(msg
						.getType())) {
					displayImage(msg.getDataPath());
				}
			}

		});

		return root;

	}

	public void displayImage(String picturePath) {
		Intent i = new Intent();
		i.setClass(getActivity(), SendPicture.class);
		i.putExtra(ChatActivity.IMAGE_DATA, picturePath);
		startActivity(i);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_SELECTED_INDEX, selectedIndex);
		outState.putString(SELECTED_NAME, selectedName);
		outState.putString(SELECTED_IP, selectedIp);
	}

	public static void displayMessage(MyMessage msg) {
		// Display the message to the UI
		adapterChat.addMessage(msg);
		adapterChat.notifyDataSetChanged();

	}

	public static void sendMessage(String path, long time,
			MyMessage.MessageType type) {

		String ip = getMyIp();
		String name = getMyName();
		Identification me = new Identification(ip, name, 0);
		Identification you = new Identification(selectedIp, selectedName, 0);

		if (selectedIp.equals(UDPBroadcastSender.GENERIC_BROADCAST_ADDRESS)) {
			DBController cont = new DBController(
					WalkieTalkieApplication.getContext());
			ArrayList<Identification> contacts = cont.getAllContacts();
			cont.close();
			for (Identification contact : contacts) {
				MyMessage message = new MyMessage(me, time, type, contact, path);
				displayMessage(message);
				// Send the message to specific contact
				TCPClientFileTransfer fct = new TCPClientFileTransfer(message);
				Thread fctThread = new Thread(fct);
				fctThread.start();
			}
		} else {
			// Create a MyMessage to send via the network
			MyMessage message = new MyMessage(me, time, type, you, path);
			displayMessage(message);

			// Send the message to just one client
			TCPClientFileTransfer fct = new TCPClientFileTransfer(message);
			Thread fctThread = new Thread(fct);
			fctThread.start();
		}
	}

	@Override
	public void UpdateMessageView(final MyMessage msg) {
		Handler mainHandler = new Handler(WalkieTalkieApplication.getContext()
				.getMainLooper());
		Runnable myRunnable = new Runnable() {
			@Override
			public void run() {
				displayMessage(msg);
			}
		};
		mainHandler.post(myRunnable);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("ChatFragment", "requestCode" + requestCode + "resultCode"
				+ resultCode);
		if (requestCode == MyCamera.CAM_REQUEST) {
			Log.e("ChatFragment", "+++++++++++++ Camera Result +++");
			cam.savePhoto("");
			// displayMessage(path, System.currentTimeMillis(),
			// MyMessage.TYPE.TYPE_PICTURE);

		} else {
			super.onActivityResult(requestCode, resultCode, data);
		}

	}

	static public ChatMessageAdapter getChatAdapter() {
		return adapterChat;
	}

	public interface IMessageListFragment {
		public void onMessageItemSelected(int position);

	}

}
